package com.bit.springblogdemo.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Map;
@Slf4j
public class JwtUtils { //生成token
    private static String SECRET_StRING = "PePYs62rKqwdz4/igHMsPdYMtupjVpVQIGt8E3ClOvI="; //这里是生成的固定的Key

    private static Key key = Keys.hmacShaKeyFor(SECRET_StRING.getBytes(StandardCharsets.UTF_8));
    public static String genToken(Map<String, Object> map) {
        String con = Jwts.builder()
                .setClaims(map)
                .signWith(key)
                .compact();
        return con;
    }

    public static Claims parseToken(String token) {  //校验token
        if(!StringUtils.hasLength(token)) {
            return null;
        }
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e) {
            log.error("token解析失败,token:"+ token);
        }
        return claims;
    }
 }
